package controller;

import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import pojo.Taikhoan;
import util.BeanUtil;
import dao.TaikhoanDAO;
import dao.TaikhoanadminDAO;

@ManagedBean(name = "taiKhoanDangNhapBean")
@SessionScoped
public class TaiKhoanDangNhapBean implements Serializable {

	private static final long serialVersionUID = 1L;
	private boolean daDangNhap = false;
	private boolean isAdmin = false;
	private String currUsername = "user10";
	private String currPassword = "matkhau11";
	private Taikhoan currTaiKhoan;// = (new TaikhoanDAO()).get(10);

	public boolean isDaDangNhap() {
		return daDangNhap;
	}

	public String DangNhap() {
		TaikhoanDAO taikhoanDAO = new TaikhoanDAO();
		Taikhoan AcceptTK = taikhoanDAO.AcceptTaiKhoan(getCurrUsername(),
				getCurrPassword());

		FacesContext context = FacesContext.getCurrentInstance();
		if (AcceptTK != null) {
			if (AcceptTK.isBanned()) {
				context.addMessage(
						null,
						new FacesMessage(
								"TÃ i khoáº£n cá»§a báº¡n Ä‘Ã£ bá»‹ cáº¥m sá»­ dá»¥ng."));
				return (null);
			}

			currTaiKhoan = AcceptTK;
			daDangNhap = true;

			TaikhoanadminDAO taikhoanadminDAO = new TaikhoanadminDAO();
			setAdmin(taikhoanadminDAO.isAdminAccount(AcceptTK));

		} else {
			context.addMessage(
					null,
					new FacesMessage(
							"Tài khoản đăng nhập / Mật khẩu bạn vừa nhập không chính xác! Vui lòng nhập lại."));
			return (null);
		}

		System.out.println("username:" + currUsername + "-" + currPassword
				+ "la admin: " + isAdmin());

		// Clear Dữ liệu trong Giỏ hàng nếu có
		if (null != (GioHangBean) BeanUtil.findBean("gioHangbean"))
			((GioHangBean) BeanUtil.findBean("gioHangbean")).XoaGioHang();
		return "TrangChu";
		// return "AdminHome";
	}

	public String DangXuat() {
		daDangNhap = false;
		setAdmin(false);
		currUsername = null;
		currPassword = null;
		currTaiKhoan = null;

		return "TrangChu";
	}

	public void setDaDangNhap(boolean daDangNhap) {
		this.daDangNhap = daDangNhap;
	}

	public Taikhoan getTaiKhoan() {
		return currTaiKhoan;
	}

	public void setTaiKhoan(Taikhoan taiKhoan) {
		this.currTaiKhoan = taiKhoan;
	}

	public String getCurrUsername() {
		return currUsername;
	}

	public void setCurrUsername(String currUsername) {
		this.currUsername = currUsername;
	}

	public String getCurrPassword() {
		return currPassword;
	}

	public void setCurrPassword(String currPassword) {
		this.currPassword = currPassword;
	}

	public boolean isAdmin() {
		return isAdmin;
	}

	public void setAdmin(boolean isAdmin) {
		this.isAdmin = isAdmin;
	}
}
